package com.example.demo.shiro;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.example.demo.bean.Admin;
import com.example.demo.bean.Permissions;
import com.example.demo.bean.Role;
import com.example.demo.dao.AdminMapper;
import com.example.demo.dao.DfyzWebsiteRoleMapper;
import com.example.demo.service.AdminService;


/**
 * 自定义Realm，实现授权与认证
 */
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private AdminService userService;
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private DfyzWebsiteRoleMapper dfyzWebsiteRoleMapper;

    /**
     * 用户授权
     **/
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(
        PrincipalCollection principalCollection) {
        
        System.out.println("===执行授权===");

        Subject subject = SecurityUtils.getSubject();
        Admin user = (Admin)subject.getPrincipal();
        if(user != null){
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            // 角色与权限字符串集合
            Set<String> rolesCollection = new HashSet<>();
            Set<String> premissionCollection = new HashSet<>();
			// 读取并赋值用户角色与权限
            Set<Role> roles = user.getRoles();
            for(Role role : roles){
                rolesCollection.add(role.getRole());
                Set<Permissions> permissions = role.getPermissions();
                for (Permissions permission : permissions){
                    premissionCollection.add(permission.getPname());
                }
                info.addStringPermissions(premissionCollection);
            }
            info.addRoles(rolesCollection);
            return info;
        }
        return null;
    }

    /**
     * 用户认证
     **/
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(
        AuthenticationToken authenticationToken) {

        System.out.println("===执行认证===");

        UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;
        Admin bean2 = userService.queryAdminOne(new HashMap() {{put("username", token.getUsername());}});
        Admin findById = adminMapper.findById(Integer.toString(bean2.getId()));

        if(findById == null){
            throw new UnknownAccountException();
        }

        ByteSource credentialsSalt = ByteSource.Util.bytes(findById.getUsername());

        return new SimpleAuthenticationInfo(findById, findById.getPassword(),
                credentialsSalt, getName());
    }

//      // 用户名
//       // 模拟Shiro用户加密，假设用户密码为123456
    public static void main(String[] args){
       String username = "test";
        // 用户密码
        String password = "test";
        // 加密方式
        String hashAlgorithName = "MD5";
        // 加密次数
        int hashIterations = 1024;
        ByteSource credentialsSalt = ByteSource.Util.bytes(username);
        Object obj = new SimpleHash(hashAlgorithName, password, 
                                    credentialsSalt, hashIterations);
        System.out.println(obj);
    }
}

